/**
 * Created by 黄忠园 on 2017/12/25.
 */
angular.module('module.repair')
    .controller('RepairRecordController', RepairRecordController)
    .controller('RepairDetailController', RepairDetailController)
    .controller('RepairEvaluateController', RepairEvaluateController)
;
RepairRecordController.$inject = ['$scope','$state', '$localStorage','$interval', 'JobJobInfoService', 'WmoperationInfoPromoterinfoService', 'JobJobDispatchService'];
RepairDetailController.$inject = ['$stateParams', 'JobJobInfoService', 'WmoperationInfoPromoterinfoService', 'JobJobDispatchService', 'JobJobCommunicationService'];
RepairEvaluateController.$inject = ['$state', '$stateParams', '$localStorage', 'JobJobCommunicationService'];
function RepairRecordController($scope,$state, $localStorage,$interval, JobJobInfoService, WmoperationInfoPromoterinfoService, JobJobDispatchService) {
    var vm = this;
    if (!$localStorage[environmental + "shopid"]) {
        $localStorage.$reset();
        $state.go('login');
    }
    var shopid = $localStorage[environmental + "shopid"];
    var divscroll = document.getElementById('scroll');//获取滚动区域
    var LoadAnimation = document.getElementById('LoadAnimation');//获取加载动画
    LoadAnimation.style.display = 'block';
    var hasload = true;//上拉防抖动
    var haschangeLabelPage = false;//是否切换标签页，默认无
    vm.messageVisible = false; // 提示框初始化
    vm.cancelBtn = cancelBtn; // 提示框取消按钮
    vm.sureBtn = sureBtn; // 提示框确认按钮
    vm.wait = []; // 待接单列表
    vm.already = []; // 已接单列表
    vm.waitassess = []; // 待评价列表
    vm.alreadyassess = []; // 已评价列表
    vm.all = [];
    var current_LabelPage = "all";//当前标签页
    vm.changeLabelPage = changeLabelPage;
    var allpage = 1;//总记录页码
    var waitpage = 1;//待接单页码
    var alreadypage = 1;//已接单页码
    var waitassesspage = 1;//待评价页码
    var alreadyassesspage = 1;//已评价页码
    var allstorage = [],waitstorage = [],alreadystorage = [],waitassessstorage = [],alreadyassessstorage = [];//标签页对应存储
    var allHeight = 0,waitHeight = 0,alreadyHeight = 0,waitassessHeight = 0,alreadyassessHeight = 0;//标签页对应滚动高度
    var alltimer,waittimer,alreadytimer,waitassesstimer,alreadyassesstimer;//滚动条回滚前定时器


    init();//初始化加载全部数据

    // 获取记录方法
    function getorder() {
         switch (current_LabelPage){
            case "all":
                JobJobInfoService.getAllOrder(shopid,allpage).$promise.then(function (data) {
                    console.log("all全部更新数：",data.length,"查询页：",allpage)
                    hasload = true;
                    LoadAnimation.style.display = 'none';
                    if(data.length > 0){
                        allstorage = data;
                        allpage++;
                        getrepairinfo(allstorage,0);
                        vm.all = vm.all.concat(allstorage);
                    }else if(data.length == 0){
                        hasload_fun();
                    };
                    change_scrollTop();
                    allstorage = [];
                },function(error){
                    LoadAnimation.style.display = 'none';
                    vm.messageVisible = true;
                    vm.message = "获取数据失败！";
                })
                break;
          case "wait":
                JobJobInfoService.getAllOrderByJobstatus(shopid,0,waitpage).$promise.then(function (data) {
                    console.log("wait全部更新数：",data.length,"查询页：",waitpage)
                    hasload = true;
                    LoadAnimation.style.display = 'none';
                    if(data.length > 0){
                        waitstorage = data;
                        waitpage++;
                        getrepairinfo(waitstorage,0);
                        vm.wait = vm.wait.concat(waitstorage);
                    }else if(data.length == 0){
                        hasload_fun();
                    };
                    change_scrollTop();
                    waitstorage = [];
                },function(error){
                    LoadAnimation.style.display = 'none';
                    vm.messageVisible = true;
                    vm.message = "获取数据失败！";
                })
              break;
            case "already":
                JobJobInfoService.getAllOrderByJobstatus(shopid,1,alreadypage).$promise.then(function (data) {
                    console.log("already全部更新数：",data.length,"查询页：",alreadypage)
                    hasload = true;
                    LoadAnimation.style.display = 'none';
                    if(data.length > 0){
                        alreadystorage = data;
                        alreadypage++;
                        getrepairinfo(alreadystorage,0);
                        vm.already = vm.already.concat(alreadystorage);
                    }else if(data.length == 0){
                        hasload_fun();
                    };
                    change_scrollTop();
                    alreadystorage = [];
                },function(error){
                    LoadAnimation.style.display = 'none';
                    vm.messageVisible = true;
                    vm.message = "获取数据失败！";
                })
                break;
            case "waitassess":
                //jobstatus=3业务处理归到此处，但实际流程没有3的状态，故只查询2的状态
                JobJobInfoService.getAllOrderByJobstatus(shopid,2,waitassesspage).$promise.then(function (data) {
                    console.log("waitassess全部更新数：",data.length,"查询页：",waitassesspage)
                    hasload = true;
                    LoadAnimation.style.display = 'none';
                    if(data.length > 0){
                        waitassessstorage = data;
                        waitassesspage++;
                        getrepairinfo(waitassessstorage,0);
                        vm.waitassess = vm.waitassess.concat(waitassessstorage);
                    }else if(data.length == 0){
                        hasload_fun();
                    };
                    change_scrollTop();
                    waitassessstorage = [];
                },function(error){
                    LoadAnimation.style.display = 'none';
                    vm.messageVisible = true;
                    vm.message = "获取数据失败！";
                })
                break;
            case "alreadyassess":
                JobJobInfoService.getAllOrderByJobstatus(shopid,4,alreadyassesspage).$promise.then(function (data) {
                    console.log("alreadyassess全部更新数：",data.length,"查询页：",alreadyassesspage)
                    hasload = true;
                    LoadAnimation.style.display = 'none';
                    if(data.length > 0){
                        alreadyassessstorage = data;
                        alreadyassesspage++;
                        getrepairinfo(alreadyassessstorage,0);
                        vm.alreadyassess = vm.alreadyassess.concat(alreadyassessstorage);
                    }else if(data.length == 0){
                        hasload_fun();
                    };
                    change_scrollTop();
                    alreadyassessstorage = [];
                },function(error){
                    LoadAnimation.style.display = 'none';
                    vm.messageVisible = true;
                    vm.message = "获取数据失败！";
                })
                break;
        }
    }

    //向上滚动加载
    function divScroll() {
        var wholeHeight = divscroll.scrollHeight;//文档总高度
        var scrollTop = divscroll.scrollTop;
        var divHeight = divscroll.clientHeight;
        var totalhight = scrollTop + divHeight;
        if(Math.ceil(totalhight) >= wholeHeight){
            console.log('滚动到底部了！hasload:',hasload);
            //这里写动态加载的逻辑，比如Ajax请求后端返回下一个页面的内容
            if(hasload && (divscroll.scrollHeight > divscroll.clientHeight)){//从含滚动条标签页进入新标签页会触发滚动事件，故判断垂直滚动条是否存在
                hasload = false;
                init();
            }else {
                //使滚动条距离底部仍有段距离可以上拉
                divscroll.scrollTop = divscroll.scrollTop -2;
            }
        }
        if(scrollTop == 0){
            // alert                                                                   ('滚动到头部了！');
        }
    }
    divscroll.onscroll = divScroll;//监听滚动事件

    //初始化
    function init() {
        LoadAnimation.style.display = 'block';
        setTimeout(function () {
            getorder();
        },1000)
    }

    //
    function hasload_fun() {
        hasload = false;
        setTimeout(function () {
            hasload = true;
        },100)
    }

    //改变标签页
    function changeLabelPage(id) {
        if(current_LabelPage != id){
            switch (current_LabelPage){
                case "all":
                    allHeight = divscroll.scrollTop;
                    break;
                case "wait":
                    waitHeight = divscroll.scrollTop;
                    break;
                case "already":
                    alreadyHeight = divscroll.scrollTop;
                    break;
                case "waitassess":
                    waitassessHeight = divscroll.scrollTop;
                    break;
                case "alreadyassess":
                    alreadyassessHeight = divscroll.scrollTop;
                    break;
            }
            haschangeLabelPage = true;
            current_LabelPage = id;
            divscroll.scrollTop = 0;//滚动条高度初始化，防止触发底部事件
            if(vm[id].length > 0){
                LoadAnimation.style.display = 'none';
                change_scrollTop();
            }else {
                init();
            }
        }
    }

    //改变滚动条高度
    function change_scrollTop() {

        if(haschangeLabelPage){

            switch (current_LabelPage){
                case "all":
                    change_scrollTop_detail(alltimer,allHeight);
                    break;
                case "wait":
                    change_scrollTop_detail(waittimer,waitHeight);
                    break;
                case "already":
                    change_scrollTop_detail(alreadytimer,alreadyHeight);
                    break;
                case "waitassess":
                    change_scrollTop_detail(waitassesstimer,waitassessHeight);
                    break;
                case "alreadyassess":
                    change_scrollTop_detail(alreadyassesstimer,alreadyassessHeight);
                    break;
            }

            haschangeLabelPage = false;
        }
    }

    //改变滚动条高度重复的方法
    function change_scrollTop_detail(timer,height) {
        if(height > 0){
            timer = $interval(function () {
                if(divscroll.scrollHeight > divscroll.clientHeight){
                    divscroll.scrollTop = height;
                    $interval.cancel(timer)
                }
            },1000);
        }else {
            divscroll.scrollTop = 0;
        }

    }

    //获取维修信息
    function getrepairinfo(list,i) {
        if(list.length == i){
            return list;
        }
        else if (list[i] && list[i].dutyid != 0) {
            WmoperationInfoPromoterinfoService.getRepairman(list[i].dutyid).$promise.then(function (data) {
                list[i].repairman = {
                    name: data.name,
                    phone: data.phone,
                };
                JobJobDispatchService.getOrderRecord(list[i].jobid).$promise.then(function (newdata) {
                    // console.log(newdata)
                    if(newdata.length > 0){
                        list[i].repairman.time = newdata[0].dispatchtime;
                    }
                    i++;
                    getrepairinfo(list,i);
                },function(error2){
                    alert(JSON.stringify(error2))
                })
            },function (error1) {
                alert(JSON.stringify(error1))
            })
        }else if(list[i] && list[i].dutyid == 0){
            i++;
            getrepairinfo(list,i);

        }

    }


    // 启动bootstrap自带标签页插件
    $('#myTab a').click(function (e) {
        e.preventDefault();
        $(this).tab('show')
    });

    // 提示框取消按钮函数
    function cancelBtn() {
        vm.messageVisible = false;
    }

    // 提示框确认按钮函数
    function sureBtn() {
        vm.messageVisible = false;
    }
}

function RepairDetailController($stateParams, JobJobInfoService, WmoperationInfoPromoterinfoService, JobJobDispatchService, JobJobCommunicationService) {

    var vm = this;
    vm.jobid = $stateParams.jobid;
    vm.jobstatus = $stateParams.jobstatus;
    vm.messageVisible = false; // 提示框初始化
    vm.cancelBtn = cancelBtn; // 提示框取消按钮
    vm.sureBtn = sureBtn; // 提示框确认按钮

    JobJobInfoService.getOrderByJobId(vm.jobid).$promise.then(function (data) {
        vm.time1 = data.createtime;
        if (data.dutyid != 0) {

            WmoperationInfoPromoterinfoService.getRepairman(data.dutyid).$promise.then(function (repairmaninfo) {
                data.repairman = {
                    name: repairmaninfo.name,
                    phone: repairmaninfo.phone,
                };

                JobJobDispatchService.getOrderRecord(vm.jobid).$promise.then(function (newdata) {
                    for (var i = 0; i < newdata.length; i++) {
                        if (newdata[i].olddutyid == 0) {
                            data.repairman.time = newdata[i].dispatchtime;
                            vm.time2 = newdata[i].dispatchtime;
                        } else if (newdata[i].olddutyid != 0 && newdata[i].olddutyid == newdata[i].newdutyid) {
                            vm.time3 = newdata[i].dispatchtime;
                        }
                    }
                    vm.record = data;
                    if (data.jobstatus == 4) {
                        geteValuate(vm.jobid);
                    }
                }, function (error3) {
                    vm.messageVisible = false;
                    vm.message = "获取派单时间失败!";
                })
            }, function (error2) {
                vm.messageVisible = false;
                vm.message = "获取业务员信息失败!";
            })
        } else {
            vm.record = data;
            if (data.jobstatus == 4) {
                geteValuate(vm.jobid);
            }
        }
    }, function (error1) {
        vm.messageVisible = false;
        vm.message = "获取工单详细失败!";
    });

    //
    function geteValuate(jobid) {
        JobJobCommunicationService.getEvaluate(jobid).$promise.then(function (data) {
            vm.time4 = data[0].recordtime;
            vm.evaluate = data[0];
        })
    }

    // 提示框取消按钮函数
    function cancelBtn() {
        vm.messageVisible = false;
    }

    // 提示框确认按钮函数
    function sureBtn() {
        vm.messageVisible = false;
    }

    /*vm.record = {
     no:1,
     common:{
     sort:["按键","喇叭","麦克风","USB口","摄像头","指示灯","SD卡插槽","显示屏","后盖","电池"],
     evaluate:"3",
     evaluatesort:["服务态度不好","不专业","技术不好","没耐心","装备准备不齐全","上门速度慢","维修速度慢"]
     },
     text:"啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊",
     time:"2017/12/25",
     status:$stateParams.status,
     assessname:"大富大贵",
     assesstime:"2017/12/25",
     assessphone:"12345678901"
     }*/
}

function RepairEvaluateController($state, $stateParams, $localStorage, JobJobCommunicationService) {

    var vm = this;
    if (!$localStorage[environmental + "shopid"]) {
        $localStorage.$reset();
        $state.go('login');
    }
    var userid = $localStorage[environmental + "userid"];
    var shopid = $localStorage[environmental + "shopid"];
    var jobid = $stateParams.jobid;
    vm.repairmanname = $stateParams.repairmanname;
    vm.messageVisible = false; // 提示框初始化
    vm.cancelBtn = cancelBtn; // 提示框取消按钮
    vm.sureBtn = sureBtn; // 提示框确认按钮
    vm.imglist = ["images/23.png", "images/25.png", "images/22.png"];
    var imglist = ["images/28.png", "images/21.png", "images/24.png"];
    var doc = document.getElementsByName("imglist");
    vm.evaluate = 0;
    vm.text = "";
    vm.wordsnum = 0;
    vm.textChange = textChange; // 显示字数
    vm.changeImg = changeImg;
    vm.sure = sure;
    var pool = {
        0: ["服务态度不好", "不专业", "技术不好", "没耐心", "装备准备不齐全", "上门速度慢", "维修速度慢"],
        1: ["服务一般", "技术还行", "态度还行"],
        2: ["服务很好", "技术很好", "态度很好", "设备齐全", "维修速度快", "上门服务快"]
    };
    vm.prollist = ["服务很好", "技术很好", "态度很好", "设备齐全", "维修速度快", "上门服务快"];
    vm.chose = chose; // 选择prolist
    var list = []; // 存储prollist
    vm.record = {
        no: 1,
        common: {
            sort: ["按键", "喇叭", "麦克风", "USB口", "摄像头", "指示灯", "SD卡插槽", "显示屏", "后盖", "电池"],
            evaluate: "3",
            evaluatesort: ["服务态度不好", "不专业", "技术不好", "没耐心", "装备准备不齐全", "上门速度慢", "维修速度慢"]
        },
        text: "啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊",
        time: "2017/12/25",
        status: 3,
        assessname: "大富大贵",
        assesstime: "2017/12/25",
        assessphone: "12345678901"
    };

    function changeImg(index) {
        vm.prollist = pool[index];
        doc[index].getAttribute("src") == vm.imglist[index] ? function () {
            doc[index].setAttribute("src", imglist[index]);
            vm.evaluate = index + 1;
        }() : function () {
            doc[index].setAttribute("src", vm.imglist[index]);
            vm.evaluate = 0;
        }();
        reset(index);
    }

    function reset(index) {
        for (var i = 0; i < vm.imglist.length; i++) {
            if (i != index) {
                doc[i].setAttribute("src", vm.imglist[i]);
            }
        }
    }

    function chose(event, pro) {
        list = storageChose(event, pro, list);
    }

    // 显示字数
    function textChange() {
        vm.wordsnum = vm.text.length;
    }

    // 确认按钮
    function sure(text) {
        if (vm.evaluate == 0) {
            vm.messageVisible = true;
            vm.message = "请选择满意度";
        }
        else if (text.length > 100) {
            vm.messageVisible = true;
            vm.message = "问题描述字数大于100";
        }
        else {
            var content = {
                sort: vm.evaluate, // 1:不满意，2：一般，3：满意
                quickevaluation: list, // 快捷评价
                evaluation: vm.text // 具体评价内容
            };
            var info = {
                "jobid": jobid,
                "personalid": userid,
                "type": 1,
                "content": JSON.stringify(content)
            };
            JobJobCommunicationService.addCom(info).$promise.then(function (data) {
                $state.go("repairrecord");

            }, function (error) {
                vm.messageVisible = true;
                vm.message = JSON.stringify(error);
            })
        }
    }

    // 提示框取消按钮函数
    function cancelBtn() {
        vm.messageVisible = false;
    }

    // 提示框确认按钮函数
    function sureBtn() {
        vm.messageVisible = false;
    }
}